package com.platform.common.utils.pay;

import com.platform.common.config.WxPayConfig;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;

public class HttpClientBuilder {
    private CloseableHttpClient httpClient;

    private static final HttpHost proxy = null;

    public void setup() {
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(WxPayConfig.privateKeyForDecrypt);
        X509Certificate wechatPayCert = PemUtil.loadCertificate(
                new ByteArrayInputStream(WxPayConfig.getCertify().getBytes(StandardCharsets.UTF_8)));

        ArrayList<X509Certificate> wechatPayCertificates = new ArrayList<>();
        wechatPayCertificates.add(wechatPayCert);

        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(WxPayConfig.mchid, WxPayConfig.mchSerialNo, merchantPrivateKey)
                .withWechatPay(wechatPayCertificates)
                .withProxy(proxy)
                .build();
    }

    public void after() throws IOException {
        httpClient.close();
    }
}
